// pages/device-detail/index.js
const app = getApp();
const api = app.api;
const wxutil = app.wxutil;
const pageSize = 500; // 每页显示条数

Page({
  data: {
    device: {},
    profession: [
      { id: 1, name: "苏州" },
      { id: 2, name: "南京" },
      { id: 3, name: "广州" },
      { id: 4, name: "北京" },
      { id: 5, name: "浙江" },
    ],
    course: {},
    actionList: [],
    focus: false, // 获取焦点
    showAction: false, // 是否显示操作菜单
    isEnd: false,
    tabsFixed: false,
    tabIndex: 0,
    pageCourse: 1,
    isEndCourse: false,
    loading: false,
    tabsTop: 255,
  },

  onLoad(options) {
    const { deviceId, focus } = options;
    // 评论获取焦点展开键盘
    if (focus) {
      this.setData({
        focus: true,
      });
    }
    this.getSchoolDetail(deviceId);
    this.getTabsTop();
  },
   
  getImage(){
    const query = wx.createSelectorQuery()
    query.select('#myCanvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        const canvas = res[0].node
        const ctx = canvas.getContext('2d')
        canvas.width = res[0].width
        canvas.height = res[0].height
        const data = this.data.device.idle_device
        const filteredData = Object.entries(data).filter(([key, value]) => key !== '空闲');
        const cities = filteredData.map(([key, value]) => key);
        const devices = filteredData.map(([key, value]) => value);
        const maxDeviceCount = Math.max(...devices)
        const barWidth = (canvas.width - 40) / cities.length
        const barHeightRatio = (canvas.height - 40) / maxDeviceCount
        ctx.fillStyle = '#337559'
      
        for (let i = 0; i < cities.length; i++) {
          const x = 20 + barWidth * i + (barWidth - 10) / 2
          const y = canvas.height - devices[i] * barHeightRatio - 20
          const barHeight = devices[i] * barHeightRatio
          ctx.fillRect(x - (barWidth - 10) / 2, y, barWidth - 10, barHeight)
          ctx.fillText(devices[i].toString(), x-10, y - 10)
          ctx.fillText(cities[i], x-10, canvas.height-5)
        }
      })
  },

  /**
   * 获取Tabs的高度
   */
  getTabsTop() {
    const navigateHeight = 56;
    const query = wx.createSelectorQuery();
    query.select("#tabs").boundingClientRect((res) => {
      this.setData({
        tabsTop: res.top - navigateHeight,
      });
    }).exec();
  },

  onPageScroll(event) {
    if (event.scrollTop >= this.data.tabsTop) {
      this.setData({
        tabsFixed: true,
      });
    } else {
      this.setData({
        tabsFixed: false,
      });
    }
  },

  /**
   * 跳转详情页
   */
  onJoinTap(event) {
    const { id } = event.currentTarget.dataset;
    wx.setStorageSync('deviceInfo', this.data.course[id]);
    wx.navigateTo({
      url: "/pages/rent-device/index",
    });
  },

  /**
   * 获取动态详情
   */
  getSchoolDetail(schoolId) {
    const url = api.deviceAPI + schoolId + "/";

    wxutil.request.get(url).then((res) => {
      if (res.data.code == 200) {
        const device = res.data.data;
        this.setData({
          device: device,
        });
        this.getCourse();
      }
    });
  },

  /**
   * 图片预览
   */
  previewImage(event) {
    const { src } = event.currentTarget.dataset;
    const { image } = this.data.device;

    wx.previewImage({
      current: src,
      urls: image,
    });
  },

  getCourse(pageCourse = 1, size = pageSize) {
    const url = api.deviceAPI + "item/";

    if (this.data.isEndCourse && pageCourse != 1) {
      return;
    }

    const { name } = this.data.profession[this.data.tabIndex];

    const data = JSON.stringify({
      area: name,
      deviceName: this.data.device.device_name,
      size: size,
      page: pageCourse,
    });

    wxutil.request.post(url, data).then((res) => {
      if (res.data.code == 200) {
        const course = res.data.data;
        console.log(course)
        const result = course.map((element) => {
          const { area, rent_price, user_devices } = element;
          return {
            device_length: user_devices.length,
            area,
            rent_price,
            device_info: user_devices[0],
          };
        });

        const updatedCourse = pageCourse == 1 ? result : this.data.course.concat(result);

        this.setData({
          pageCourse: course.length == 0 && pageCourse != 1 ? pageCourse - 1 : pageCourse,
          loading: false,
          isEndCourse: (course.length < pageSize) || (course.length == 0 && pageCourse != 1),
          course: updatedCourse,
        });
      }
    });
  },

  /**
   * 展开操作菜单
   */
  onMoreTap() {
    const actionList = [{
      name: "分享",
      color: "#666",
      openType: "share",
    }];

    this.setData({
      showAction: true,
      actionList: actionList,
    });
  },

  changeTabs(event) {
    const { currentIndex } = event.detail;
    this.setData({
      tabIndex: currentIndex,
    });
    this.getCourse();
  },

  /**
   * 触底加载
   */
  onReachBottom() {
    this.setData({
      loading: true,
    });
    const page = this.data.pageCourse;
    this.getCourse(page + 1);
  },

  /**
   * 关闭操作菜单
   */
  onCancelSheetTap() {
    this.setData({
      showAction: false,
    });
  },

  onShareAppMessage() {
    return {
      title: this.data.device.device_name,
      imageUrl: this.data.device.image,
      path: "/pages/device-detail/index?deviceId=" + this.data.device.id,
    };
  },
});
